package kr.saeildamil.androidforstudy2.ch33;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import kr.saeildamil.androidforstudy2.R;
import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class CameraTest extends Activity {
	MyCameraSurface mSurface;
	Button mShutter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch33_camera);
		
		mSurface = (MyCameraSurface) findViewById(R.id.preview);
		
		findViewById(R.id.focus).setOnClickListener(new Button.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mShutter.setEnabled(false);
				mSurface.camera.autoFocus(mAutoFocus);
			}
		});
	
		mShutter.findViewById(R.id.shutter);
		mShutter.setOnClickListener(new Button.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mSurface.camera.takePicture(null, null, mPicture);
			}
		});
	}
	
	AutoFocusCallback mAutoFocus = new AutoFocusCallback() {
		
		@Override
		public void onAutoFocus(boolean success, Camera camera) {
			mSurface.setEnabled(success);
		}
	};
	
	PictureCallback mPicture = new PictureCallback() {
		
		@Override
		public void onPictureTaken(byte[] data, Camera camera) {
			String sd = Environment.getExternalStorageDirectory().getAbsolutePath();
			String sdpath = sd + "/cameratest.jpg";
			File file = new File(sdpath);
			try {
				FileOutputStream fos = new FileOutputStream(file);
				fos.write(data);
				fos.flush();
				fos.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			// MediaDB 갱신;
			Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
			Uri uri = Uri.parse("file://" + sdpath);
			intent.setData(uri);
			sendBroadcast(intent);
			
			Toast.makeText(CameraTest.this, "Saved successfully" + sdpath, Toast.LENGTH_SHORT).show();
			mSurface.camera.startPreview();
		}
	};
}
